package com.dog.threesixty;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.dog.share.twitter.TwitterShareManager;
import com.dog.utils.Constants;
import com.dog.utils.NoRepeatRandom;
import com.dog.utils.Utils;
import com.fb.android.FacebookShareManager;
import com.dog.utils.Downloader;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class LearningQuizeActivity extends Activity implements OnClickListener {

	private TextView timerView;
	private TextView tView;
	private TextView scoreView;
	private TextView quesTextView;
	private TextView alertView;
	private TextView miliView;
	private TextView congratulationView;
	private TextView whatView;

	private ImageView pauseView;
	private ImageView imageView;
	private ImageView animView;
	private ImageView facebookButton;
	private ImageView twitterButton;

	private Button firstButton;
	private Button secondButton;
	private Button thirdButton;
	private Button fourthButton;

	private int currentIndex = -1;
	private int countCorrectAns = 0;
	private int score = 0;
	private int bonusScore;
	private int level;
	private int randomValue;
	private int targetPosition[];
	private int imagesToShow[] = { R.drawable.dog1_2x, R.drawable.dog2_2x,
			R.drawable.dog3_2x, R.drawable.dog4_2x, R.drawable.dog5_2x,
			R.drawable.dog6_2x, R.drawable.dog7_2x, R.drawable.dog8_2x,
			R.drawable.dog9_2x, R.drawable.dog10_2x, R.drawable.dog11_2x,
			R.drawable.dog12_2x, R.drawable.dog13_2x, R.drawable.dog14_2x };

	private long remainingTime = 0;

	private boolean isNext = true;
	private int quizeIndex = -1;
	private boolean isNextQuestion = true;
	private int numOfQuestion;
	private boolean isPause;
	private boolean isTimer;
	private boolean isClick;
	private boolean isExit;
	private boolean isAnim;
	private boolean isNextLevel;

	private String DIRECTORY = "";
	private String jsonString;
	private String fileName;
	private String compareText;
	private String IMAGE_DIRECTORY;

	private NoRepeatRandom nrr;
	private CountDownTimer timer;
	private ImplementQuiz iquiz;
	private File files[];
	private List<int[]> positionList;

	private JSONArray ja;
	private JSONObject jo;
	private boolean isFilesDownloaded[] = new boolean[18];

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.layout_quize);

			isFilesDownloaded = Utils
					.getFilesDownloaded(LearningQuizeActivity.this);

			congratulationView = (TextView) findViewById(R.id.congratulationView);
			alertView = (TextView) findViewById(R.id.alertView);
			imageView = (ImageView) findViewById(R.id.imageView);
			timerView = (TextView) findViewById(R.id.timerView);
			tView = (TextView) findViewById(R.id.tView);
			scoreView = (TextView) findViewById(R.id.scoreView);
			scoreView.setTextColor(Color.GREEN);
			whatView = (TextView) findViewById(R.id.whatView);

			quesTextView = (TextView) findViewById(R.id.questionNumberView);
			quesTextView.setTextColor(Color.GREEN);

			pauseView = (ImageView) findViewById(R.id.pauseView);
			pauseView.setOnClickListener(this);

			firstButton = (Button) findViewById(R.id.firstButton);
			firstButton.setOnClickListener(this);

			secondButton = (Button) findViewById(R.id.secondButton);
			secondButton.setOnClickListener(this);

			thirdButton = (Button) findViewById(R.id.thirdButton);
			thirdButton.setOnClickListener(this);

			fourthButton = (Button) findViewById(R.id.fourthButton);
			fourthButton.setOnClickListener(this);

			facebookButton = (ImageView) findViewById(R.id.facebook_Button);
			facebookButton.setOnClickListener(this);

			twitterButton = (ImageView) findViewById(R.id.twitter_Button);
			twitterButton.setOnClickListener(this);

			positionList = new ArrayList<int[]>();

			isTimer = getIntent()
					.getBooleanExtra(Constants.KEY_IS_TIMER, false);
			if (!isTimer) {
				timerView.setVisibility(View.GONE);
				findViewById(R.id.tView).setVisibility(View.GONE);
			}
			level = getIntent().getIntExtra(Constants.KEY_LEVEL, 0);

			jsonString = getJsonString(level);
//			 getJSONObjectForRandomLevel();

			// implementQuize();
			iquiz = new ImplementQuiz(quizeIndex, Constants.WAITING_TIME);
			iquiz.execute("" + quizeIndex);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			isExit = true;
			Intent intent = new Intent(LearningQuizeActivity.this,
					LearningBeforeActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra(Constants.KEY_QUIZ, Constants.QUIZ_LEARNING);
			startActivity(intent);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	class ImplementQuiz extends AsyncTask<String, String, String> {

		private int currentIndex;
		private long waitingTime;
		private String option1;
		private String option2;
		private String option3;
		private String option4;
		private String firstText;
		private String secondText;
		private String thirdText;
		private String fourthText;

		public ImplementQuiz(int currentIndex, long waitingTime) {
			super();
			this.currentIndex = currentIndex;
			this.waitingTime = waitingTime;
		}

		protected void onProgressUpdate(String... arg0) {
			try {

				quizeIndex = currentIndex;
				currentIndex++;
				isClick = true;
				Log.i("DREG", "Current Index=" + currentIndex);

				whatView.setText("What is highlighted?");
				firstButton.setBackgroundResource(R.drawable.quize_button);
				secondButton.setBackgroundResource(R.drawable.quize_button);
				thirdButton.setBackgroundResource(R.drawable.quize_button);
				fourthButton.setBackgroundResource(R.drawable.quize_button);

				firstButton.setTextColor(Color.WHITE);
				secondButton.setTextColor(Color.WHITE);
				thirdButton.setTextColor(Color.WHITE);
				fourthButton.setTextColor(Color.WHITE);

				firstButton.setEnabled(true);
				secondButton.setEnabled(true);
				thirdButton.setEnabled(true);
				fourthButton.setEnabled(true);

				if (isTimer) {
					showTimer(waitingTime);
				}

				if (currentIndex < (ja.length())) {

					isNext = false;
					quesTextView
							.setText((currentIndex + 1) + "/" + ja.length());

					Log.i("DREG", "Random value = " + randomValue);
					fileName = ja.getJSONObject(
							positionList.get(currentIndex)[0]).getString(
							"-part");
					imageView.setImageURI(Uri.parse(getFilePath(fileName)));

					switch (randomValue) {
					case 0:
						firstButton.setText(ja.getJSONObject(
								positionList.get(currentIndex)[0]).getString(
								"-part"));
						secondButton.setText(ja.getJSONObject(
								positionList.get(currentIndex)[1]).getString(
								"-part"));
						thirdButton.setText(ja.getJSONObject(
								positionList.get(currentIndex)[2]).getString(
								"-part"));
						fourthButton.setText(ja.getJSONObject(
								positionList.get(currentIndex)[3]).getString(
								"-part"));
						break;
					case 1:
						firstButton.setText(ja.getJSONObject(
								positionList.get(currentIndex)[1]).getString(
								"-part"));
						secondButton.setText(ja.getJSONObject(
								positionList.get(currentIndex)[0]).getString(
								"-part"));
						thirdButton.setText(ja.getJSONObject(
								positionList.get(currentIndex)[2]).getString(
								"-part"));
						fourthButton.setText(ja.getJSONObject(
								positionList.get(currentIndex)[3]).getString(
								"-part"));
						break;
					case 2:
						firstButton.setText(ja.getJSONObject(
								positionList.get(currentIndex)[2]).getString(
								"-part"));
						secondButton.setText(ja.getJSONObject(
								positionList.get(currentIndex)[1]).getString(
								"-part"));
						thirdButton.setText(ja.getJSONObject(
								positionList.get(currentIndex)[0]).getString(
								"-part"));
						fourthButton.setText(ja.getJSONObject(
								positionList.get(currentIndex)[3]).getString(
								"-part"));

						break;
					case 3:
						firstButton.setText(ja.getJSONObject(
								positionList.get(currentIndex)[3]).getString(
								"-part"));
						secondButton.setText(ja.getJSONObject(
								positionList.get(currentIndex)[1]).getString(
								"-part"));
						thirdButton.setText(ja.getJSONObject(
								positionList.get(currentIndex)[2]).getString(
								"-part"));
						fourthButton.setText(ja.getJSONObject(
								positionList.get(currentIndex)[0]).getString(
								"-part"));

						break;

					default:
						break;
					}

				} else {
					timerView.setVisibility(View.INVISIBLE);
					tView.setVisibility(View.INVISIBLE);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		protected String doInBackground(String... arg0) {
			try {
				if (isTimer) {
					while ((currentIndex < (ja.length() - 1)) && (!isExit)) {
						Random random = new Random();
						randomValue = random.nextInt(4);
						if (!isPause) {
							publishProgress("");
						}
						Thread.sleep(waitingTime);

					}
				}

				else {
					while ((currentIndex < (ja.length())) && (!isExit)) {
						if (isNextQuestion) {
							isNextQuestion = false;
							Random random = new Random();
							randomValue = random.nextInt(4);
							if (currentIndex != -1) {
								Thread.sleep(Constants.POST_CLICK_TIME);
							}
							publishProgress("");
							Thread.sleep(Constants.PRE_CLICK_TIME);
						}
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String unused) {

			int percent = (int) ((countCorrectAns * 100) / numOfQuestion);

			imageView.setBackgroundColor(Color.parseColor("#313131"));
			imageView.setAlpha(0x88);
			firstButton.setText("Main Menu");
			secondButton.setText("Try again");

			firstButton.setBackgroundResource(R.drawable.quize_button);
			secondButton.setBackgroundResource(R.drawable.quize_button);
			// thirdButton.setBackgroundResource(R.drawable.quize_button);
			// fourthButton.setBackgroundResource(R.drawable.quize_button);
			thirdButton.setVisibility(View.INVISIBLE);
			fourthButton.setVisibility(View.INVISIBLE);
			facebookButton.setVisibility(View.VISIBLE);
			twitterButton.setVisibility(View.VISIBLE);

			firstButton.setTextColor(Color.WHITE);
			secondButton.setTextColor(Color.WHITE);
			thirdButton.setTextColor(Color.WHITE);
			fourthButton.setTextColor(Color.WHITE);

			firstButton.setEnabled(true);
			secondButton.setEnabled(true);
			thirdButton.setEnabled(true);
			fourthButton.setEnabled(true);

			timerView.setVisibility(View.INVISIBLE);
			tView.setVisibility(View.INVISIBLE);
			thirdButton.setBackgroundResource(R.drawable.btn_facebook);
			thirdButton.setText("");
			fourthButton.setBackgroundResource(R.drawable.btn_twitter);
			fourthButton.setText("");
			alertView.setVisibility(View.VISIBLE);
			if (percent < 70) {
				isNextLevel = false;
				congratulationView.setText("Sorry :)");
				alertView.setText("You only scored " + score + " points with "
						+ percent + "% accuracy.");
			} else {
				isNextLevel = true;
				secondButton.setText("Next Level");
				congratulationView.setText("Congratulations !");
				alertView.setText("You have scored " + score + " points with "
						+ percent + "% accuracy.");
				int highestScore = Utils.getLevelHighestScore(
						LearningQuizeActivity.this,
						Constants.KEY_LEARNING_SCORE + level);
				if (score > highestScore) {
					Utils.putLevelHighestScore(LearningQuizeActivity.this,
							Constants.KEY_LEARNING_SCORE + level, score);
					Utils.putPrecentage(LearningQuizeActivity.this,
							Constants.KEY_LEARNING_PERCENTAGE + level, percent);
				}
			}
		}

	}

	private void buttonClicked(int position) {
		if (fileName.equalsIgnoreCase(compareText)) {
			++countCorrectAns;
			score += 10 + bonusScore;
			scoreView.setText("" + score);
			if (isTimer) {
				whatView.setText(bonusScore + " Bonus points");
			}
			if (!(thirdButton.getText().toString().equals(""))) {
				Utils.play(this, R.raw.sound_correct);
			}
			switch (position) {
			case 0:
				firstButton
						.setBackgroundResource(R.drawable.quiz_answer_correct);
				// firstButton.setTextColor(Color.GREEN);
				break;
			case 1:
				secondButton
						.setBackgroundResource(R.drawable.quiz_answer_correct);
				// secondButton.setTextColor(Color.GREEN);
				break;
			case 2:
				thirdButton
						.setBackgroundResource(R.drawable.quiz_answer_correct);
				// thirdButton.setTextColor(Color.GREEN);
				break;
			case 3:
				fourthButton
						.setBackgroundResource(R.drawable.quiz_answer_correct);
				// fourthButton.setTextColor(Color.GREEN);
				break;
			default:
				break;
			}
		} else {
			if (!(thirdButton.getText().toString().equals(""))) {
				Utils.vibratePhone(LearningQuizeActivity.this);
				Utils.play(this, R.raw.sound_incorrect);
			}
			switch (position) {
			case 0:
				firstButton.setBackgroundResource(R.drawable.quiz_answer_wrong);
				// firstButton.setTextColor(Color.RED);
				break;
			case 1:
				secondButton
						.setBackgroundResource(R.drawable.quiz_answer_wrong);
				// secondButton.setTextColor(Color.RED);
				break;
			case 2:
				thirdButton.setBackgroundResource(R.drawable.quiz_answer_wrong);
				// thirdButton.setTextColor(Color.RED);
				break;
			case 3:
				fourthButton
						.setBackgroundResource(R.drawable.quiz_answer_wrong);
				// fourthButton.setTextColor(Color.RED);
				break;
			default:
				break;
			}

			switch (randomValue) {
			case 0:
				// firstButton.setBackgroundResource(R.drawable.quiz_answer_correct);
				firstButton.setTextColor(Color.GREEN);
				break;
			case 1:
				// secondButton.setBackgroundResource(R.drawable.quiz_answer_correct);
				secondButton.setTextColor(Color.GREEN);
				break;
			case 2:
				// thirdButton.setBackgroundResource(R.drawable.quiz_answer_correct);
				thirdButton.setTextColor(Color.GREEN);
				break;
			case 3:
				// fourthButton.setBackgroundResource(R.drawable.quiz_answer_correct);
				fourthButton.setTextColor(Color.GREEN);
				break;
			default:
				break;
			}
		}

		if (isTimer) {
			try {
				new AsyncTask<String, String, String>() {
					@Override
					protected void onPreExecute() {
						try {
							iquiz.cancel(true);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					@Override
					protected String doInBackground(String... arg0) {
						try {
							Log.i("DREG", "Quize Index =" + quizeIndex);
							if (quizeIndex < (numOfQuestion - 2)) {
								Thread.sleep(Constants.WAITING_FOR_NEXT);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						return null;
					}

					@Override
					protected void onPostExecute(String unused) {
						isClick = false;
						if (quizeIndex < (numOfQuestion - 1)) {
							iquiz = new ImplementQuiz(++quizeIndex,
									Constants.WAITING_TIME);
						}
						iquiz.execute();
					}
				}.execute();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onClick(View v) {
		String text = thirdButton.getText().toString();
		int viewId = v.getId();
		if ((viewId == R.id.firstButton) || (viewId == R.id.secondButton)
				|| (viewId == R.id.thirdButton)
				|| (viewId == R.id.fourthButton)) {
			if (!text.equals("")) {
				firstButton.setEnabled(false);
				secondButton.setEnabled(false);
				thirdButton.setEnabled(false);
				fourthButton.setEnabled(false);
			}

			if (isTimer) {
				timer.cancel();
				// waitForNext = Math.min(remainingTime, 1000);
			}

		}
		switch (viewId) {
		case R.id.firstButton:
			if (!text.equals("")) {
				if (isClick) {

					compareText = firstButton.getText().toString();
					buttonClicked(0);
					isClick = false;
					isNextQuestion = true;
					isNext = true;
				}
			} else {
				isExit = true;
				imageView.setAlpha(0xFF);
				Intent backIntent = new Intent(LearningQuizeActivity.this,
						LearningBeforeActivity.class);
				backIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(backIntent);
			}
			break;
		case R.id.secondButton:
			if (!text.equals("")) {
				if (isClick) {
					if (isTimer) {
						timer.cancel();
					}
					compareText = secondButton.getText().toString();
					buttonClicked(1);
					isClick = false;
					isNext = true;
					isNextQuestion = true;

				}
			} else {
				// if (isTimer) {
				// timer.cancel();
				// }
				currentIndex = -1;
				isExit = false;
				isNext = true;
				score = 0;
				scoreView.setText("" + score);
				imageView.setAlpha(0xFF);
				alertView.setVisibility(View.GONE);
				quesTextView.setVisibility(View.VISIBLE);
				if (!isNextLevel) {
					Intent intent = new Intent(LearningQuizeActivity.this,
							LearningQuizeActivity.class);
					intent.putExtra(Constants.KEY_IS_TIMER, isTimer);
					intent.putExtra(Constants.KEY_LEVEL, level);
					startActivity(intent);
					// implementQuize();
				} else {

					++level;
					// files = Downloader.getFileList(IMAGE_DIRECTORY);
					// Log.i("DREG", "File length=" + files.length);
					if (level != 17) {
						if (isFilesDownloaded[level]) {
							Intent intent = new Intent(
									LearningQuizeActivity.this,
									LearningQuizeActivity.class);
							Log.i("DREG", "is Normal=" + isTimer);
							intent.putExtra(Constants.KEY_IS_TIMER, isTimer);
							intent.putExtra(Constants.KEY_LEVEL, level);
							startActivity(intent);
						} else {
							Intent backIntent = new Intent(
									LearningQuizeActivity.this,
									LearningBeforeActivity.class);
							backIntent
									.putExtra(Constants.KEY_NEXT_LEVEL, level);
							backIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(backIntent);
						}
					} else {
						Toast.makeText(LearningQuizeActivity.this,
								"No next level to play", Toast.LENGTH_LONG)
								.show();
					}

				}
			}
			break;
		case R.id.thirdButton:
			if (!text.equals("")) {
				if (isClick) {
					if (isTimer) {
						timer.cancel();
					}
					compareText = thirdButton.getText().toString();
					buttonClicked(2);
					isClick = false;
					isNext = true;
					isNextQuestion = true;

				}
			}
			// else {
			// // timer.cancel();
			// faceBookSharing("I have just scored " + score + " in Horse 360");
			// }
			break;
		case R.id.facebook_Button:
			faceBookSharing("I have just scored " + score + " in Horse 360");
			break;
		case R.id.fourthButton:
			if (!text.equals("")) {
				if (isClick) {
					if (isTimer) {
						timer.cancel();
					}
					compareText = fourthButton.getText().toString();
					buttonClicked(3);
					isClick = false;
					isNext = true;
					isNextQuestion = true;

				}
			} else {
				shareInTwitter();
			}
			break;
		case R.id.twitter_Button:
			shareInTwitter();
			break;
		case R.id.pauseView:
			if (isTimer) {
				timer.cancel();
				iquiz.cancel(true);
				isPause = true;
			}

			showPausePopUp();
			break;

		default:
			break;

		}

	}

	private String getJsonString(int level) {
		String jsonFileName = "";
		try {

			switch (level) {
			case 0:
				DIRECTORY = Constants.PACK1_DIRECTORY;
				jsonFileName = "General 1 Quiz 1.json";
				break;
			case 1:
				DIRECTORY = Constants.PACK1_DIRECTORY;
				jsonFileName = "General 2 Quiz 1.json";
				break;
			case 2:
				DIRECTORY = Constants.PACK1_DIRECTORY;
				jsonFileName = "General 3 Quiz 1.json";
				break;
			case 3:
				DIRECTORY = Constants.PACK1_DIRECTORY;
				jsonFileName = "Conformation 1 Quiz 1.json";
				break;
			case 4:
				DIRECTORY = Constants.PACK2_DIRECTORY;
				jsonFileName = "Conformation 2 Quiz 1.json";
				break;
			case 5:
				DIRECTORY = Constants.PACK2_DIRECTORY;
				jsonFileName = "Conformation 3 Quiz 1.json";
				break;
			case 6:
				DIRECTORY = Constants.PACK2_DIRECTORY;
				jsonFileName = "Conformation 4 Quiz 1.json";
				break;
			case 7:
				DIRECTORY = Constants.PACK2_DIRECTORY;
				jsonFileName = "Skeleton 1 Quiz 1.json";
				break;
			case 8:
				DIRECTORY = Constants.PACK3_DIRECTORY;
				jsonFileName = "Skeleton 2 Quiz 1.json";
				break;
			case 9:
				DIRECTORY = Constants.PACK3_DIRECTORY;
				jsonFileName = "Super Muscles 1 Quiz 1.json";
				break;
			case 10:
				DIRECTORY = Constants.PACK3_DIRECTORY;
				jsonFileName = "Super Muscles 2 Quiz 1.json";
				break;
			case 11:
				DIRECTORY = Constants.PACK4_DIRECTORY;
				jsonFileName = "Deep Muscles 1 Quiz 1.json";
				break;
			case 12:
				DIRECTORY = Constants.PACK4_DIRECTORY;
				jsonFileName = "Deep Muscles 2 Quiz 1.json";
				break;
			case 13:
				DIRECTORY = Constants.PACK4_DIRECTORY;
				jsonFileName = "Skull Quiz 1.json";
				break;
			case 14:
				DIRECTORY = Constants.PACK5_DIRECTORY;
				jsonFileName = "Teeth Quiz 1.json";
				break;
			case 15:
				DIRECTORY = Constants.PACK5_DIRECTORY;
				jsonFileName = "Organs 1 Quiz 1.json";
				break;
			case 16:
				DIRECTORY = Constants.PACK5_DIRECTORY;
				jsonFileName = "Organs 2 Quiz 1.json";
				break;
			case 17:
				DIRECTORY = Constants.PACK1_DIRECTORY;
				jsonFileName = "Random Quiz 1.json";
				break;

			default:
				jsonFileName = "Level 1-Quiz 1.json";
				break;
			}

			if (level != 17) {
				jo = new JSONObject(new String(Utils.getFileData(this,
						jsonFileName)));
			} else {
				jo = getJSONObjectForRandomLevel();
			}

			try {

				ja = jo.getJSONObject("root").getJSONArray("dog");
				numOfQuestion = ja.length();
				// for (int k = 0; k < ja.length(); k++) {
				// String fileName = ja.getJSONObject(k).getString("-parent");
				// Log.i("DREG", "fileName = " + Utils.getFileName(fileName));
				// }

				nrr = new NoRepeatRandom(0, ja.length() - 1);
				for (int i = 0; i < ja.length(); i++) {
					int testValue[] = new int[4];

					testValue[0] = nrr.GetRandom();

					int count = 0;
					NoRepeatRandom n = new NoRepeatRandom(0, ja.length() - 1);
					for (int j = 0; j < ja.length(); j++) {
						int untargetValue = n.GetRandom();
						if (untargetValue != testValue[0] && count <= 2) {
							testValue[++count] = untargetValue;
						}
					}

					positionList.add(testValue);
				}

				// for (int k = 0; k < positionList.size(); k++) {
				// Log.i("DREG",
				// "1st = " + positionList.get(k)[0] + " 2nd ="
				// + positionList.get(k)[1] + " 3rd ="
				// + positionList.get(k)[2] + " 4th ="
				// + positionList.get(k)[3]);
				// }

			} catch (Exception e) {
				e.printStackTrace();
			}

			return jo.toString();
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}

	private JSONObject getJSONObjectForRandomLevel() {

		JSONObject randJob = new JSONObject();
		JSONArray dogA = new JSONArray();
		JSONObject rootJob = new JSONObject();
		try {
			JSONObject jo = new JSONObject(new String(Utils.getFileData(this,
					"Random Learning.json")));
			JSONArray ja = jo.getJSONObject("root").getJSONArray("dog");

			if (Utils.containsAllFiles(Constants.PACK1_DIRECTORY, Arrays
					.asList(Utils.getImageFileName(LearningQuizeActivity.this,
							Constants.PACK1_JSON_FILE)))) {
				for (int i = 0; i < 49; i++) {
					JSONObject jOb = new JSONObject();
					String part = ja.getJSONObject(i).getString("-part");
					String parent = ja.getJSONObject(i).getString("-parent");
					jOb.put("-part", part);
					jOb.put("-parent", parent);
					dogA.put(jOb);
				}
			}
			if (Utils.containsAllFiles(Constants.PACK2_DIRECTORY, Arrays
					.asList(Utils.getImageFileName(LearningQuizeActivity.this,
							Constants.PACK2_JSON_FILE)))) {
				for (int i = 49; i < 94; i++) {

					JSONObject jOb = new JSONObject();
					String part = ja.getJSONObject(i).getString("-part");
					String parent = ja.getJSONObject(i).getString("-parent");
					jOb.put("-part", part);
					jOb.put("-parent", parent);
					dogA.put(jOb);
				}
			}

			if (Utils.containsAllFiles(Constants.PACK3_DIRECTORY, Arrays
					.asList(Utils.getImageFileName(LearningQuizeActivity.this,
							Constants.PACK3_JSON_FILE)))) {
				for (int i = 94; i < 136; i++) {
					JSONObject jOb = new JSONObject();
					String part = ja.getJSONObject(i).getString("-part");
					String parent = ja.getJSONObject(i).getString("-parent");
					jOb.put("-part", part);
					jOb.put("-parent", parent);
					dogA.put(jOb);
				}
			}

			if (Utils.containsAllFiles(Constants.PACK4_DIRECTORY, Arrays
					.asList(Utils.getImageFileName(LearningQuizeActivity.this,
							Constants.PACK4_JSON_FILE)))) {
				for (int i = 136; i < 172; i++) {
					JSONObject jOb = new JSONObject();
					String part = ja.getJSONObject(i).getString("-part");
					String parent = ja.getJSONObject(i).getString("-parent");
					jOb.put("-part", part);
					jOb.put("-parent", parent);
					dogA.put(jOb);
				}
			}

			if (Utils.containsAllFiles(Constants.PACK5_DIRECTORY, Arrays
					.asList(Utils.getImageFileName(LearningQuizeActivity.this,
							Constants.PACK5_JSON_FILE)))) {
				for (int i = 172; i < ja.length(); i++) {
					JSONObject jOb = new JSONObject();
					String part = ja.getJSONObject(i).getString("-part");
					String parent = ja.getJSONObject(i).getString("-parent");
					Log.i("DREG", "Random part name=" + part);
					Log.i("DREG", "Random parent name=" + parent);
					jOb.put("-part", part);
					jOb.put("-parent", parent);
					dogA.put(jOb);
				}
			}

			randJob.put("dog", dogA);
			rootJob.put("root", randJob);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.i("DREG", "Root JSON=" + rootJob.toString());
		return rootJob;
	}

	private void showTimer(long remainingCountTime) {
		bonusScore = 0;
		timer = new CountDownTimer(remainingCountTime, 100) {

			@Override
			public void onTick(long millisUntilFinished) {
				String time = "";
				if (isClick) {
					bonusScore = (int) (Math
							.ceil((double) millisUntilFinished / 1000));
				}
				remainingTime = millisUntilFinished;
				long second = millisUntilFinished / 1000;
				long tenth = (millisUntilFinished % 1000) / 100;
				time = second + "." + tenth;
				timerView.setText(time);

			}

			@Override
			public void onFinish() {
				timerView.setText(0 + "." + 0);

			}
		}.start();

	}

	private void faceBookSharing(String message) {
		FacebookShareManager fsm = new FacebookShareManager(this, this,
				Constants.FACEBOOK_APP_ID, Constants.FACEBOOK_PERMISSION);
		fsm.shareMessage(message);

	}

	private void shareInTwitter() {
		TwitterShareManager tsm = new TwitterShareManager(
				LearningQuizeActivity.this, this);
		tsm.shareTweet("I have just score " + score + " in Horse 360");
	}

	/*
	 * private void implementQuize() { try { new AsyncTask<String, String,
	 * String>() { private JSONArray ja; private JSONObject jo;
	 * 
	 * @Override protected void onPreExecute() { try {
	 * 
	 * jo = new JSONObject(jsonString); ja =
	 * jo.getJSONObject("root").getJSONArray("dog"); for (int k = 0; k <
	 * ja.length(); k++) { String fileName = ja.getJSONObject(k).getString(
	 * "-parent"); Log.i("DREG", "fileName = " + Utils.getFileName(fileName)); }
	 * 
	 * nrr = new NoRepeatRandom(0, ja.length() - 1); for (int i = 0; i <
	 * ja.length(); i++) { int testValue[] = new int[4];
	 * 
	 * testValue[0] = nrr.GetRandom();
	 * 
	 * int count = 0; NoRepeatRandom n = new NoRepeatRandom(0, ja.length() - 1);
	 * for (int j = 0; j < ja.length(); j++) { int untargetValue =
	 * n.GetRandom(); if (untargetValue != testValue[0] && count <= 2) {
	 * testValue[++count] = untargetValue; } }
	 * 
	 * positionList.add(testValue); }
	 * 
	 * for (int k = 0; k < positionList.size(); k++) { Log.i("DREG", "1st = " +
	 * positionList.get(k)[0] + " 2nd =" + positionList.get(k)[1] + " 3rd =" +
	 * positionList.get(k)[2] + " 4th =" + positionList.get(k)[3]); }
	 * 
	 * } catch (Exception e) { e.printStackTrace(); } }
	 * 
	 * protected void onProgressUpdate(String... arg0) { try {
	 * 
	 * currentIndex++; isClick = true; Log.i("DREG", "Current Index=" +
	 * currentIndex);
	 * 
	 * firstButton .setBackgroundResource(R.drawable.quize_button); secondButton
	 * .setBackgroundResource(R.drawable.quize_button); thirdButton
	 * .setBackgroundResource(R.drawable.quize_button); fourthButton
	 * .setBackgroundResource(R.drawable.quize_button);
	 * 
	 * firstButton.setTextColor(Color.WHITE);
	 * secondButton.setTextColor(Color.WHITE);
	 * thirdButton.setTextColor(Color.WHITE);
	 * fourthButton.setTextColor(Color.WHITE);
	 * 
	 * firstButton.setEnabled(true); secondButton.setEnabled(true);
	 * thirdButton.setEnabled(true); fourthButton.setEnabled(true);
	 * 
	 * if (currentIndex < ja.length()) { if (isTimer) {
	 * showTimer(Constants.WAITING_TIME); }
	 * 
	 * isNext = false; quesTextView.setText((currentIndex + 1) + "/" +
	 * ja.length());
	 * 
	 * Log.i("DREG", "Random value = " + randomValue); fileName =
	 * ja.getJSONObject( positionList.get(currentIndex)[0]) .getString("-part");
	 * imageView.setImageURI(Uri.parse(getFilePath( DIRECTORY, fileName)));
	 * 
	 * switch (randomValue) { case 0: firstButton.setText(ja.getJSONObject(
	 * positionList.get(currentIndex)[0]) .getString("-part"));
	 * secondButton.setText(ja.getJSONObject( positionList.get(currentIndex)[1])
	 * .getString("-part")); thirdButton.setText(ja.getJSONObject(
	 * positionList.get(currentIndex)[2]) .getString("-part"));
	 * fourthButton.setText(ja.getJSONObject( positionList.get(currentIndex)[3])
	 * .getString("-part")); break; case 1:
	 * firstButton.setText(ja.getJSONObject( positionList.get(currentIndex)[1])
	 * .getString("-part")); secondButton.setText(ja.getJSONObject(
	 * positionList.get(currentIndex)[0]) .getString("-part"));
	 * thirdButton.setText(ja.getJSONObject( positionList.get(currentIndex)[2])
	 * .getString("-part")); fourthButton.setText(ja.getJSONObject(
	 * positionList.get(currentIndex)[3]) .getString("-part")); break; case 2:
	 * firstButton.setText(ja.getJSONObject( positionList.get(currentIndex)[2])
	 * .getString("-part")); secondButton.setText(ja.getJSONObject(
	 * positionList.get(currentIndex)[1]) .getString("-part"));
	 * thirdButton.setText(ja.getJSONObject( positionList.get(currentIndex)[0])
	 * .getString("-part")); fourthButton.setText(ja.getJSONObject(
	 * positionList.get(currentIndex)[3]) .getString("-part"));
	 * 
	 * break; case 3: firstButton.setText(ja.getJSONObject(
	 * positionList.get(currentIndex)[3]) .getString("-part"));
	 * secondButton.setText(ja.getJSONObject( positionList.get(currentIndex)[1])
	 * .getString("-part")); thirdButton.setText(ja.getJSONObject(
	 * positionList.get(currentIndex)[2]) .getString("-part"));
	 * fourthButton.setText(ja.getJSONObject( positionList.get(currentIndex)[0])
	 * .getString("-part"));
	 * 
	 * break;
	 * 
	 * default: break; } } } catch (Exception e) { e.printStackTrace(); } }
	 * 
	 * @Override protected String doInBackground(String... arg0) { try {
	 * 
	 * while ((currentIndex < ja.length()) && (!isExit)) { if (isTimer) { Random
	 * random = new Random(); randomValue = random.nextInt(4); if (!isPause) {
	 * publishProgress(""); } Thread.sleep(Constants.WAITING_TIME); } else { if
	 * (isNext) { Random random = new Random(); randomValue = random.nextInt(4);
	 * if (currentIndex != -1) { Thread.sleep(Constants.POST_CLICK_TIME); }
	 * publishProgress(""); Thread.sleep(Constants.PRE_CLICK_TIME);
	 * 
	 * } } }
	 * 
	 * } catch (Exception e) { e.printStackTrace(); } return null; }
	 * 
	 * @Override protected void onPostExecute(String unused) {
	 * 
	 * int percent = (int) ((score * 100) / (ja.length() * 10)); //
	 * quesTextView.setVisibility(View.GONE); imageView.setAlpha(0x7F);
	 * firstButton.setText("Main Menu"); secondButton.setText("Try again");
	 * timerView.setText("0.0");
	 * thirdButton.setBackgroundResource(R.drawable.btn_facebook);
	 * thirdButton.setText("");
	 * fourthButton.setBackgroundResource(R.drawable.btn_twitter);
	 * fourthButton.setText(""); alertView.setVisibility(View.VISIBLE); if
	 * (percent < 70) { isNextLevel = false;
	 * alertView.setText("Sorry,you only scored " + score + " points with " +
	 * percent + "% accuracy."); } else { isNextLevel = true;
	 * secondButton.setText("Next Level");
	 * alertView.setText("Congratulations,you have scored " + score +
	 * " points with " + percent + "% accuracy."); int highestScore =
	 * Utils.getLevelHighestScore( LearingQuizeActivity.this,
	 * Constants.KEY_LEARNING_SCORE + level); if (score > highestScore) {
	 * Utils.putLevelHighestScore( LearingQuizeActivity.this,
	 * Constants.KEY_LEARNING_SCORE + level, score);
	 * Utils.putPrecentage(LearingQuizeActivity.this,
	 * Constants.KEY_LEARNING_PERCENTAGE + level, percent); } } } }.execute();
	 * 
	 * } catch (Exception e) { e.printStackTrace(); } }
	 */

	private void showPausePopUp() {
		isAnim = false;
		LayoutInflater factory = LayoutInflater.from(this);
		View dialog = factory.inflate(R.layout.layout_pause_screen, null);

		ImageView resumeView = (ImageView) dialog.findViewById(R.id.resumeView);
		Button menuButton = (Button) dialog.findViewById(R.id.menuButton);
		animView = (ImageView) dialog.findViewById(R.id.imageView);

		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setCancelable(false);
		final AlertDialog alert = alt_bld.create();
		alert.getWindow().setFlags(
				android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN,
				android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN);

		resumeView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (isTimer) {
					isAnim = true;
					isPause = false;

					isPause = false;
					// isNextQuestion = true;
					if (isTimer) {
						Log.i("DREG", "Remaining time =" + remainingTime);
						iquiz = new ImplementQuiz(quizeIndex, remainingTime);
						iquiz.execute();
					}

				}
				alert.cancel();

			}
		});

		menuButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				alert.cancel();
				isAnim = true;
				isExit = true;
				Intent intent = new Intent(LearningQuizeActivity.this,
						LearningBeforeActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intent.putExtra(Constants.KEY_QUIZ, Constants.QUIZ_LEARNING);
				startActivity(intent);

			}
		});
		showImageInPeriod();
		alert.setView(dialog);
		alert.show();
	}

	private void showImageInPeriod() {
		try {
			new AsyncTask<String, String, String>() {
				private boolean isInvisible;
				private int index;

				@Override
				protected void onPreExecute() {
					try {
						index = 0;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				protected void onProgressUpdate(String... arg0) {
					animView.setBackgroundResource(imagesToShow[index]);

				}

				@Override
				protected String doInBackground(String... arg0) {
					try {
						while (!isAnim) {
							if (index < (imagesToShow.length - 1)) {
								index++;
							} else {
								index = 0;
							}
							publishProgress("");
							Thread.sleep(4000);

						}

					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					return null;
				}

				@Override
				protected void onPostExecute(String unused) {
				}
			}.execute();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String getFilePath(String fileName) {
		boolean isFound = false;
		fileName = fileName + ".png";
		String path = "";

		if (!isFound) {
			File files[] = Downloader.getFileList(Constants.PACK1_DIRECTORY);
			if (files != null) {
				for (int i = 0; i < files.length; i++) {
					if (files[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = files[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		if (!isFound) {
			File files[] = Downloader.getFileList(Constants.PACK2_DIRECTORY);
			if (files != null) {
				for (int i = 0; i < files.length; i++) {
					if (files[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = files[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		if (!isFound) {
			File files[] = Downloader.getFileList(Constants.PACK3_DIRECTORY);
			if (files != null) {
				for (int i = 0; i < files.length; i++) {
					if (files[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = files[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		if (!isFound) {
			File files[] = Downloader.getFileList(Constants.PACK4_DIRECTORY);
			if (files != null) {
				for (int i = 0; i < files.length; i++) {
					if (files[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = files[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		if (!isFound) {
			File files[] = Downloader.getFileList(Constants.PACK5_DIRECTORY);
			if (files != null) {
				for (int i = 0; i < files.length; i++) {
					if (files[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = files[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		return path;
	}

}
